// pages/MaintainAdd/MaintainAdd.js
let httpRequest = require('../../utils/http_utils.js')
let regeneratorRuntime = require('../../utils/runtime.js');
let utils = require('../../utils/util')
let CryptoJS = require('../../utils/aes_util.js') //参数加密
let dateutil = require('../../utils/date_util.js')


Page({

  /**
   * 页面的初始数据
   */
  data: {
    title: '添加维保记录',
    items: [{
      name: '正常',
      value: '正常'
    },
    {
      name: '异常',
      value: '异常'
    }
    ],
    itemInfo: [],
    TaskState: 1,
    tag: true,
  },

  radioChange: function (e) {
    console.log('radio发生change事件，携带value值为：', e.detail.value)
    let index = e.currentTarget.dataset.index;

    let itemInfo = this.data.itemInfo;
    itemInfo[index].ItemResultContent = e.detail.value
    this.setData({
      itemInfo: itemInfo
    })
  },

  Open: function (e) {
    let selected = e.currentTarget.dataset.selected;
    let index = e.currentTarget.dataset.index;
    let itemInfo = this.data.itemInfo;
    itemInfo[index].selected = !selected
    console.log("itemInfo打开" + JSON.stringify(itemInfo))
    this.setData({
      itemInfo: itemInfo
    })
  },

  TaskRemark: function (e) {
    this.setData({
      TaskRemark: e.detail.value
    })
  },

  ItemResultRemarks: function (e) {
    let index = e.currentTarget.dataset.index;
    let itemInfo = this.data.itemInfo;
    itemInfo[index].ItemResultRemarks = e.detail.value
    this.setData({
      itemInfo: itemInfo
    })
  },

  // 新增维保记录
  addrecord: async function () {
    let that = this;
    let itemInfo = this.data.itemInfo;

    for (let item of itemInfo) {
      if (utils.isEmptyObject(item.ItemResultContent)){
        that.setData({
          error: '维保项结果不能为空'
        })
        return 
      }
    }

    let Param = {
      TaskGuid: that.data.TaskGuid,
      Recorder: that.data.Recorder,
      TaskState: that.data.TaskState,
      itemInfo: that.data.itemInfo,
      TaskRemark: that.data.TaskRemark,
    }
    console.log(JSON.stringify(Param))
    let data = await utils.post(httpRequest.apiInfo.AddRecordListApi, Param)
    console.log(data)

    if (!utils.isEmptyObject(data.data)) {
      if (data.data == 2) {
        that.setData({
          error: '当前维保记录为空，新增失败！'
        })
      } else if (data.data == 1) {
        that.setData({
          error: '新增失败！'
        })
      } else if (data.data == 0) {
        that.setData({
          success: '新增成功！'
        })
        setTimeout(() => {
          wx.navigateBack({
            delta: 1
          })
        }, 1000)

      }
    }

  },

  GetMaintenanceTerm: async function () {
    var that = this;
    var Param = {
      TaskGuid: that.data.TaskGuid,
    }
    console.log("参数" + JSON.stringify(Param))
    let data = await utils.get(httpRequest.apiInfo.GetMaintenanceTermApi + "?" + CryptoJS.AesEncrypt(Param))
    console.log("GetMaintenanceTerm" + JSON.stringify(data.data))
    let itemInfo = data.data
    if (!utils.isEmptyObject(itemInfo)) {
      itemInfo.map((item, i) => {
        item.selected = false;
        item.imgurls = [];
        item.picnum = 0;
      })
      this.setData({
        itemInfo: itemInfo
      })
    }
  },

  //选择图片
  chooseimage: function (e) {
    let that = this;
    let index = e.currentTarget.dataset.index;
    let itemInfo = this.data.itemInfo;
    console.log(index)



    let imgurls = that.data.itemInfo[index].imgurls;
    let FileGuidInfo = that.data.itemInfo[index].FileGuidInfo;

    wx.chooseImage({
      count: 9 - imgurls.length,
      sizeType: ['compressed'],
      sourceType: ['album', 'camera'],
      success(res) {
        // tempFilePath可以作为img标签的src属性显示图片
        const tempFilePaths = res.tempFilePaths
        console.log("tempFilePaths", tempFilePaths)
        for (let i = 0; i < tempFilePaths.length; i++) {
          imgurls.push(tempFilePaths[i]);

          wx.compressImage({
            src: tempFilePaths[i],
            quality: 80,
            success: function (res) {
              console.log('压缩图片', res)
              let tempFilePaths = res.tempFilePath
              const uploadFile = wx.uploadFile({
                url: httpRequest.host + httpRequest.apiInfo.MultipleFileUploadMobileApi,
                filePath: tempFilePaths,
                name: dateutil.getNowTime(),
                header: {
                  "Content-Type": "multipart/form-data"
                },
                formData: {
                  FileType: '维修记录'
                },
                success: function (res) {
                  console.log(res)
                  var param = {
                    RowGuid: JSON.parse(res.data).RowGuid,
                    FileGuid: JSON.parse(res.data).FileGuid
                  }
                  FileGuidInfo.push(param)
                },
                fail: function (err) {
                  that.setData({
                    error: '图片上传失败'
                  })
                  console.error(err)
                }
              })
              uploadFile.onProgressUpdate((res) => {
                console.log("上传进度", res.progress)
                if (res.progress == 100) {
                  wx.hideLoading()
                } else {
                  wx.showLoading({
                    title: '图片已上传' + res.progress + '%',
                  })
                }
              })
            },
            fail: function (err) {
              console.error(('压缩图片失败', err))
            }
          })
        }
        that.data.itemInfo[index].picnum = imgurls.length;
        that.setData({
          itemInfo: itemInfo,
        })
        console.log('-----itemInfo---', that.data.itemInfo)


      }
    })
  },


  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let equipmentname = options.equipmentname;
    let TaskBeginTime = options.taskbegintime;
    let TaskEndTime = options.taskendtime;
    let equipmentlocation = options.equipmentlocation;
    let recordpeople = wx.getStorageSync("UserInfo").AppLogin.DisplayName;
    let Recorder = wx.getStorageSync("UserInfo").AppLogin.RowGuid;
    let TaskGuid = options.taskguid;

    TaskBeginTime = dateutil.dateFormat(TaskBeginTime)
    TaskEndTime = dateutil.dateFormat(TaskEndTime)

    this.setData({
      equipmentname: equipmentname,
      TaskBeginTime: TaskBeginTime,
      TaskEndTime: TaskEndTime,
      equipmentlocation: equipmentlocation,
      recordpeople: recordpeople,
      Recorder: Recorder,
      TaskGuid: TaskGuid,
    })


    this.GetMaintenanceTerm()
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})